package com.jzr.task.base;

import com.jzr.task.db1.model.TSysJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

public class JobMap {
    private static Logger log = LoggerFactory.getLogger(JobMap.class);
    public static Map<String, ScheduledFuture<?>> map = new ConcurrentHashMap<>();

    public static int getSize(){
        return map.size();
    }

    public static void add(String id,ScheduledFuture<?> future){
        remove(id,true);
        map.put(id,future);
    }

    public static void remove(String id,boolean isForceStop){
        ScheduledFuture<?> future = map.get(id);
        if(future != null) {
            stop(future,isForceStop);
        }
        map.remove(id);
    }

    public static void removeAll(boolean isForceStop){
        for(Map.Entry entry : map.entrySet()){
            String id = (String)entry.getKey();
            remove(id,isForceStop);
        }
    }

    public static void stop(ScheduledFuture<?> future, boolean isForceStop){
        if(future != null && !future.isDone()){
            future.cancel(isForceStop);
        }
    }

    public static List<TSysJob> getJobList(){
        List<TSysJob> list = new ArrayList<>();
        for(Map.Entry entry : map.entrySet()){
            String id = (String) entry.getKey();
            ScheduledFuture<?> future = (ScheduledFuture<?>) entry.getValue();

            TSysJob newItem = new TSysJob();
            newItem.setId(Integer.valueOf(id));
            if(future != null) {
                newItem.setIsDone(future.isDone());
                newItem.setIsCancelled(future.isCancelled());
            }
            list.add(newItem);
        }
        return list;
    }

    public static boolean isRunning(String id){
        ScheduledFuture<?> future = map.get(id);
        if(future == null){
            return false;
        }else{
            return !future.isDone();
        }
    }

    public static boolean isCancelled(String id) {
        ScheduledFuture<?> future = map.get(id);
        if (future == null) {
            return false;
        } else {
            return future.isCancelled();
        }
    }

}
